package me.atbar.moonlib.version;

import lombok.Getter;
import org.bukkit.Bukkit;
import java.util.regex.Pattern;

/**
 * @author Administrator
 */

public enum VersionEnum {

    /**
     * VERSION field
     */
    VERSION_1_16(160),
    VERSION_1_15(150),
    VERSION_1_14(140),
    VERSION_1_13(130),
    VERSION_1_12(120),
    VERSION_1_11(110),
    VERSION_1_10(100),
    VERSION_1_9(90),
    VERSION_1_8(80),
    NOT_SUPPORT(0);

    @Getter
    private final int amount;

    VersionEnum(int amount) {
        this.amount = amount;
    }

    public static boolean support() {
        return matchVersion() != NOT_SUPPORT;
    }

    /**
     * 检测版本是否在1.12上
     *
     * @return above 1.12
     */
    public static boolean isNewVersion() {
        return matchVersion().getAmount() > 120;
    }

    public static VersionEnum matchVersion() {
        String majorVersion = getExactMajorVersion(Bukkit.getVersion());
        switch (majorVersion) {
            case "1.16": {
                return VersionEnum.VERSION_1_16;
            }
            case "1.15": {
                return VersionEnum.VERSION_1_15;
            }
            case "1.14": {
                return VersionEnum.VERSION_1_14;
            }
            case "1.13": {
                return VersionEnum.VERSION_1_13;
            }
            case "1.12": {
                return VersionEnum.VERSION_1_12;
            }
            case "1.11": {
                return VersionEnum.VERSION_1_11;
            }
            case "1.10": {
                return VersionEnum.VERSION_1_10;
            }
            case "1.9": {
                return VersionEnum.VERSION_1_9;
            }
            case "1.8": {
                return VersionEnum.VERSION_1_8;
            }
            default:
                return VersionEnum.NOT_SUPPORT;
        }
    }

    /**
     * Gets the exact major version (..., 1.9, 1.10, ..., 1.14)
     *
     * @param version Supports {@link Bukkit#getVersion()}, {@link Bukkit#getBukkitVersion()} and normal formats such as "1.14"
     * @return the exact major version.
     */
    private static String getExactMajorVersion(String version) {
        if (version.contains("SNAPSHOT") || version.contains("-R")) {
            version = version.substring(0, version.indexOf("-"));
        }
        if (version.contains("git")) {
            version = version.substring(version.indexOf("MC:") + 4).replace(")", "");
        }
        if (version.split(Pattern.quote(".")).length > 2) {
            version = version.substring(0, version.lastIndexOf("."));
        }
        return version;
    }

}
